package com.jch.case2.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

//TODO:不需要被访问，因此不要加路径
//@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求资源路径
        String uri = request.getRequestURI();// /user/findAll  /user/update
        //2.获取uri表示的最后一个/的索引
        int lastIndex = uri.lastIndexOf("/");
        //3.根据上述获取的最后一个/的索引截取最后/下个字符一直到字符串末尾 findAll update
        //参数lastIndex + 1==》这里+1的原因是我们向截取最后一个/的下哥字符开始一直到字符串uri的末尾
        String methodName = uri.substring(lastIndex + 1);
        //TODO:使用反射执行上述过多if语句问题
        try {
            //4.获取当前类的Class对象
            //TODO:这里的this表示当前类的对象即User1Servlet类的对象
            Class<?> clazz = this.getClass();
            //5.获取要执行的方法
            //methodName =  方法名 delete add  update findAll
            Method m = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //6.执行方法
            m.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
